package cn.com.anysdk.starter.config.map;

import cn.com.anysdk.map.config.BaiduMapConfig;
import cn.com.anysdk.map.exception.MapConfigException;
import cn.com.anysdk.map.service.BaiduMapService;
import cn.com.anysdk.map.service.MapService;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.util.Timeout;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 百度地图自动配置类
 */
@Configuration
@EnableConfigurationProperties(BaiduMapProperties.class)
@ConditionalOnProperty(prefix = "anysdk.map.baidu", name = "enabled", havingValue = "true")
public class BaiduMapAutoConfiguration {

    @Bean
    public CloseableHttpClient baiduMapHttpClient() {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(100);
        connectionManager.setDefaultMaxPerRoute(20);
        return HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(org.apache.hc.client5.http.config.RequestConfig.custom()
                        .setConnectTimeout(Timeout.ofMilliseconds(5000))
                        .setResponseTimeout(Timeout.ofMilliseconds(5000))
                        .build())
                .build();
    }

    @Bean
    public BaiduMapConfig baiduMapConfig(BaiduMapProperties properties) {
        if (properties.getAk() == null || properties.getAk().trim().isEmpty()) {
            throw new MapConfigException("Baidu Map AK is required");
        }

        BaiduMapConfig config = new BaiduMapConfig();
        config.setEnabled(properties.isEnabled());
        config.setAk(properties.getAk());
        config.setSk(properties.getSk());
        config.setTimeout(Timeout.ofDays(properties.getTimeout()));
        config.setRetryTimes(properties.getRetryTimes());
        config.setRetryInterval(properties.getRetryInterval());
        return config;
    }

    @Bean
    public MapService baiduMapService(BaiduMapConfig config, CloseableHttpClient httpClient) {
        return new BaiduMapService(config, httpClient);
    }
}

